package com.aote.entity.model;

import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aote.util.StringHelper;
import com.browsesoft.Entity;
import com.browsesoft.EntityManager;
import com.browsesoft.Tools;
import com.browsesoft.baseadapter.HTMLLazyTableModel;
import com.browsesoft.dbtools.DBTools;
import com.browsesoft.oa.DisposeSelectResult;
import com.browsesoft.util.ComponentHelper;

/**
 * 选择实体，初始选择结果在http请求的ids参数中。
 */
public class EntitySelectTableModel extends HTMLLazyTableModel {
	/**
	 * 选择结果处理器
	 */
	private DisposeSelectResult disposeSelectResult = null;

	public void init(HttpServletRequest request) throws Exception {
		super.init(request);
		// 取得要选择结果的组件
		this.disposeSelectResult = ComponentHelper
				.getDisposeSelectResult(request);
	}

	/**
	 * 设置默认选择项
	 */
	private void setDefaultSelections(HttpServletRequest request) {
		// 把初始选择结果给选择结果
		String ids = request.getParameter("ids");
		// 仅第一次设置，以后不设置
		if (ids == null || ids.equals("")) {
			return;
		}
		// 产生sql条件，根据条件加载对象，sql条件=预置条件+ids条件
		ids = StringHelper.addQuote(ids);
		String prevCond = this.component.getElement().getAttribute(
				"SQLCondition");
		String cond = "selfid in (" + ids + ")";
		cond = DBTools.connectCondition(prevCond, cond);
		// 找到所有初始选择的对象
		Iterator iter = EntityManager.getInstance().getEntities(
				this.entityType, cond).iterator();
		while (iter.hasNext()) {
			// 初始选择传进来的是不同版本，相同对象的id，转换成本模型中的对象id号
			Entity entity = (Entity)iter.next();
			String id = entity.getID();
			changed.add(id);
		}
	}

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		super.service(request, response);
		setDefaultSelections(request);
		// 是选择请求，把选择结果交给发起选择的组件，关闭窗口
		if (action != null && action.equals("select")) {
			String ids = Tools.LinkedListTostring(this.changed);
			this.disposeSelectResult.dispose(ids);
			this.component.getPage().close();
		}
	}
}
